/*
 * @Author: your name
 * @Date: 2021-04-01 16:55:02
 * @LastEditTime: 2021-04-16 11:33:44
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \web\node\route\sowing.js
 */
import express from "express";
import Source from "./../models/Source";
import config from "./../src/config";
import { basename } from "path";
import formidable from "formidable";
const route = express.Router({});

/**************************** 接口API *************************/
/* 上传图片的接口 */
route.post("/back/source/api/add_img", (req, res, next) => {
  let form = new formidable.IncomingForm();
  form.uploadDir = config.uploadsPath;
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return next(err);
    }

    if (files.image_url) {
      let image_url =
        "http://localhost:3000/uploads/" + basename(files.image_url.path);
      res.json({
        status: 200,
        result: image_url,
      });
    } else {
      res.json({
        status: -1,
        result: "图片上传失败！",
      });
    }
  });
});

/* 新增一个文章 */
route.post("/back/source/api/source_add", (req, res, next) => {
  let form = new formidable.IncomingForm();
  form.uploadDir = config.uploadsPath;
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return next(err);
    }
    // 1. 取出普通字段
    let body = fields;
    // 2. 解析上传的文件路径, 取出文件名保存到数据库
    body.small_img = basename(files.small_img.path);
    // 3. 操作数据库
    // 操作数据库
    let source = new Source({
      title: body.title,
      author: body.author,
      small_img: body.small_img,
      price: body.price,
      content: body.content,
    });
    source.save((err, result) => {
      if (err) {
        return next(err);
      }
      res.json({
        status: 200,
        result: "添加轮播图成功",
      });
    });
  });
});

/* 根据id查询一篇文章资源数据 */
route.get("/back/source/api/single/:sourceId", (req, res, next) => {
  Source.find(
    { _id: req.params.sourceId },
    "_id title small_img  author is_store price content",
    (err, docs) => {
      if (err) {
        return next(err);
      }
      res.json({
        status: 200,
        result: docs,
      });
    }
  );
});

/* 根据id去修改一篇文章资源数据 */
route.post("/back/source/api/edit", (req, res, next) => {
  const form = new formidable.IncomingForm();
  form.uploadDir = config.uploadsPath;
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return next(err);
    }
    let body = fields;

    Source.findById(body.id, (err, source) => {
      // 名称
      (source.title = body.title),
        // 缩略图
        (source.small_img = body.small_img || basename(files.small_img.path)),
        // 作者
        (source.author = body.author),
        // 价格
        (source.price = body.price),
        // 内容
        (source.content = body.content),
        //最后编辑时间
        (source.l_time = new Date());

      source.save((err, result) => {
        if (err) {
          return next(err);
        }
        res.json({
          status: 200,
          result: "文章修改成功",
        });
      });
    });
  });
});

/* 根据id去删除一篇文章资源数据 */
route.get("/back/source/api/delete/:sourceId", (req, res, next) => {
  Source.deleteOne({ _id: req.params.sourceId }, (err, result) => {
    if (err) {
      return next(err);
    }
    if (result.ok === 1) {
      res.json({
        status: 200,
        result: "轮播图删除成功！",
      });
    }
  });
});

/* 前端获取记录总数 */
route.get("/web/source/api/count", (req, res, next) => {
  Source.countDocuments((err, count) => {
    if (err) {
      return next(err);
    }
    res.json({
      status: 200,
      result: count,
    });
  });
});

/* 前端获取资源列表 */
route.get("/web/source/api/list", (req, res, next) => {
  //1. 接收客户端传递的数据
  let { page, pageSize, sortBy } = req.query;
  page = Number.parseInt(page, 10) || 1;
  pageSize = Number.parseInt(pageSize, 10) || 10;

  //2.指定查询规则
  let sortObj = { read_count: -1 };
  if (sortBy === "price") {
    sortObj = { price: -1 };
  } else {
    sortObj = { read_count: -1 };
  }

  //3.查询操作
  Source.find({}, "title small_img price")
    .sort(sortObj)
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .exec((err, sources) => {
      if (err) {
        return next(err);
      }
      res.json({
        status: 200,
        result: sources,
      });
    });
});

/* 前端获取文章详情列表 */
route.get("/web/source/api/content/:sourceId", (req, res, next) => {
  console.log(req.params.sourceId)


  Source.findById(req.params.sourceId, "title author read_count add_time content", (err,source)=>{
    if (err) {
      return next(err);
    }
    res.json({
      status: 200,
      result: source,
    });
  })
});

/* 前端阅读量处理 */
route.get("/web/source/api/content/read_count/:sourceId", (req, res, next) => {

  Source.findById(req.params.sourceId, "read_count", (err,source)=>{
    if (err) {
      return next(err);
    }

    source.read_count += 1;

    source.save((err,result)=>{
      if (err) {
        return next(err);
      }
      res.json({
        status:200,
        result:"阅读量更新成功！"
      })
    })

  })
});

/**************************** 页面路由 *************************/

/* 加载文章资源管理页面 */
route.get("/back/source_list", (req, res, next) => {
  Source.find((err, sources) => {
    if (err) {
      return next(err);
    }
    res.render("back/source_list.html", { sources });
  });
});

/* 加载添加文章资源界面 */
route.get("/back/source_add", (req, res, next) => {
  res.render("back/source_add.html");
});

/* 加载修改轮播图界面 */
route.get("/back/source_edit", (req, res, next) => {
  res.render("back/source_edit.html");
});

export default route;
